<template>
  <view @click="closeList">
    <l-background />

    <view v-if="type==='remark'" class="padding-top-30">
      <add-order-cell v-model="form.remark" unlined label="订单备注" placeholder="请输入订单备注" />
    </view>

    <template v-else-if="ioType">
      <l-tab-bar id="tabBar" :tabs="tabs" :active-inx.sync="activeInx" />

      <swiper :style="{height:height+'px'}" :current="activeInx" :duration="300" @change="onswiperchange">
        <swiper-item>
          <scroll-view :style="{height:sHeight+'px'}" scroll-y>
            <view class="add-new-container">
              <!-- 订单基本信息 -->
              <view class="card margin-bottom-14">
                <order-info-module type="edit" :data="form" :module="module" :stop-site="stopSite" @update="updateFormData" @changeDate="setDate" />
              </view>
              <!-- 用户信息 -->
              <view class="card customer-module margin-bottom-14">
                <order-customer-module ref="customerModule" :flag="flag" :data="form" @update="updateFormData" />
              </view>
              <!-- 车辆信息 -->
              <view class="margin-bottom-14">
                <order-vehicle-module
                  ref="vehicleModule"
                  :data="form"
                  :show-del="false"
                  :start-date="form.startDate"
                  :end-date="form.endDate"
                  :show-platform-driver="showPlatformDriver"
                  @choose="choose"
                  @update="updateFormData"
                />
              </view>
            </view>
          </scroll-view>
        </swiper-item>
        <swiper-item>
          <scroll-view :style="{height:sHeight+'px'}" scroll-y>
            <view class="add-new-container">
              <view class="card">
                <order-other-module :data="form" :value="productsIndex" type="edit" @update="updateFormData" />
              </view>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </template>

    <view v-else class="padding-top-30">
      <view class="margin-bottom-14">
        <order-vehicle-module-sf
          ref="vehicleModule"
          :data="form"
          :show-del="false"
          :start-date="form.startDate"
          :end-date="form.endDate"
          :show-platform-driver="showPlatformDriver"
          @choose="choose"
          @update="updateFormData"
        />
      </view>
      <add-order-cell v-model="form.originPrice" hasSlot label="车费" placeholder="请输入车费" must >{{form.originPrice}}</add-order-cell>
      <add-order-cell v-if="orderInfo.type == 8" v-model="form.driverSubsidyAmount" hasSlot label="司机补助" placeholder="请输入司机补助" >{{form.driverSubsidyAmount}}</add-order-cell>
	   <add-order-cell v-else v-model="form.driverSubsidyAmount" label="司机补助" placeholder="请输入司机补助" ></add-order-cell>
      <add-order-cell v-model="form.driverRemark" label="司机备注" placeholder="请输入司机备注" />
      <add-order-cell v-model="form.remark" unlined label="订单备注" maxlength="200" placeholder="请输入订单备注" />
    </view>

    <safe-area-bottom id="safe" />

    <l-bottom-button text="确认" :disabled="!canCreate" @click="creatOrder">
      <view v-if="showProtocol" class="padding-bottom-20">
        <l-check-box v-model="isRead">
          <view slot="after" class="flex-row align-center" @click="isRead=!isRead">
            <text class="text-24 color-t3">我已阅读并同意</text>
            <text class="text-24 color-primary" @click.stop="showAgreement = true">《{{ name }}司机协议》</text>
          </view>
        </l-check-box>
      </view>
    </l-bottom-button>

    <tui-modal
      :show="showModal"
      title="提示"
      content="当前司机该时间段处于离职或休假状态"
      :button="[{text:'确定'}]"
      @click="showModal=false"
      @cancel="showModal=false"
    />

    <driver-agreement :show.sync="showAgreement" @confirm="isRead=true" />
    <bz-date-picker :value="start" :days="92" :min-time="minStartDate" type="start" :default-time="startDate" :minute-step="10" @confirm="startDateConfirm" @cancel="close('start')" @close="close('start')" />
    <bz-date-picker v-if="endTimeShow" :value="end" :days="92" :min-time="form.startDate.replace(/-/g,'/') || minStartDate" type="end" :default-time="endDate" :minute-step="10" @confirm="endDateConfirm" @cancel="close('end')" @close="close('end')" />
  </view>
</template>

<script>
import OrderCustomerModule from '../components/order-customer-module/order-customer-module'
import OrderInfoModule from '../components/order-info-module/order-info-module'
import OrderVehicleModule from '../components/order-vehicle-module/order-vehicle-module'
import OrderVehicleModuleSf from '../components/order-vehicle-module-sf/order-vehicle-module.vue'
import OrderOtherModule from '../components/order-other-module/order-other-module'
import DriverAgreement from '../components/driver-agreement/driver-agreement'
import AddOrderCell from '../components/add-order-cell/add-order-cell'
import { mapGetters, mapMutations } from 'vuex'
import { dateFormat, loading, checkDate } from '@/common/util'
import { bindJudgmentVehicle, bindJudgment, bindDriver } from '@/common/api/car'
import { products } from '../index'
import { updateOrderAll, getOrderDetail, updateOrderRemark } from '../api'
import { name } from '@/common/config'
export default {
  name: 'Edit',
  components: {
    OrderInfoModule,
    OrderVehicleModule,
    OrderOtherModule,
    DriverAgreement,
    AddOrderCell,
	OrderVehicleModuleSf,//20230815  待完成不可编辑，新增组件
    OrderCustomerModule
  },
  data() {
    const today = new Date()
    const tomorrow = today.getTime() + (1000 * 60 * 60 * 24)

    const date = new Date(tomorrow)
    date.setMinutes(0)
    const start = date.setHours(6)
    const end = date.setHours(21)

    const minStart = new Date(today.setDate(today.getDate() - 30))
    minStart.setHours(0)
    minStart.setMinutes(0)
    const minStartDate = dateFormat(minStart, 'YYYY/MM/DD hh:mm')
    const startDate = dateFormat(new Date(start), 'YYYY/MM/DD hh:mm')
    const endDate = dateFormat(new Date(end), 'YYYY/MM/DD hh:mm')
    return {
      name,
      orderId: '',
      orderInfo: {},
      type: '',
      loading: null,
      tabs: [
        { title: '用车信息' },
        { title: '订单信息' }
      ],
	  flag: false,
      activeInx: 0,
      showModal: false,
      module: 0, // 模板类型 0:模板一  1:模板二
      form: {
        companyHookOrderId: '', // 获客订单Id
        startDate: '', // 出发时间
        endDate: '', // 结束时间
        from: '', // 出发点请求数据
        fromLat: '', // 出发点请求数据
        fromLnt: '', // 出发点请求数据
        stopSite: [], // 停靠点
        to: '', // 到达点请求数据
        toLat: '', // 到达点请求数据
        toLnt: '', // 到达点请求数据
        itinerary: '', // 行程路线
        payWay: 3, // 支付方式
        username: '', // 乘车客户名称
        customerPhone: '', // 乘车客户电话
        internalProductType: products[0].value, // 产品
        internalProductTypeLabel: products[0].name, // 产品名称
        pickUpNum: 1, // 接送趟次
        itineraryUrl: '', // 行程单
        contact: '', // 联系人/导游
        phone: '', // 乘车联系人电话
        remark: '', // 订单备注
        isTaoTuan: false, // 套团
        roundType: 1, // 出团往返类型 1：单程，2：往返
        driverId: '', // 司机id
        driverName: '', // 司机名称
        driverRemark: '', // 司机备注
        driverSubsidyAmount: '', // 司机补助
        passengers: '', // 乘车人数
        realPrice: '', // 车费
        vehicleName: '', // 车辆名称
        vehicleId: '', // 车辆id
        platformDriverFee: '', // 司机费用
        vehicleType: 0, // 车辆类型 0-自有车辆 1-外调车辆
        driverType: 0, // 司机类型 0-自有司机 1-平台司机 2-外调司机
        // 外调表单
        autoCompanyName: '', // 车企名称
        seatNum: '', // 座位数
        driverPhone: '', // 司机电话
        outwardRealPrice: '', // 外调车辆费用
        originPrice: '', // 订单价格
        ioType: '',
        autoBrand: ''
      },
      productsIndex: '', // 产品下标
      stopSite: '', // 停靠点
      oldPrice: '', // 旧价格
      ioType: '', // 订单类型
      endTimeShow: true, // 是否加载结束时间选择框
      start: false, // 开始时间弹窗
      end: false, // 结束时间弹窗
      height: 0, // 内容高度
      canCreate: true, // 是否可创建
      showAgreement: false, // 展示司机协议
      isRead: false, // 是否选中司机协议
      minStartDate, // 最小可选择时间
      startDate, // 默认开始时间
      endDate // 默认结束时间
    }
  },
  computed: {
    mustList() {
      return [ // 校验列表
        { placeholder: '请选择出发时间', value: 'startDate', condition: () => true },
        { placeholder: '请选择结束时间', value: 'endDate', condition: () => true },
        { placeholder: '请输入行程路线', value: 'itinerary', condition: () => this.module === 0 },
        { placeholder: '请选择出发地', value: 'from', condition: () => this.module === 1 },
        { placeholder: '请选择目的地', value: 'to', condition: () => this.module === 1 },
        { placeholder: '请输入客户名称', value: 'username', condition: () => this.form.payWay == 3 },
        { placeholder: '请输入接送趟次', value: 'pickUpNum', condition: () => this.form.internalProductType == 3 }
      ]
    },
    // 滚动区域高度
    sHeight() {
      return this.height - this.px()
    },
    // 是否显示平台司机
    showPlatformDriver() {
      if (this.form.endDate) {
        const now = new Date().getTime()
        const end = new Date(this.form.endDate.replace(/-/g, '/')).getTime()
        return end > now
      }
      return true
    },
    // 是否展示协议
    showProtocol() {
      return !this.form.vehicleType && this.form.driverType === 1 && this.type !== 'remark'
    },
    ...mapGetters({
      chooseVehicleInfo: 'chooseVehicleInfo',
      chooseDriverInfo: 'chooseDriverInfo'
    })
  },
  watch: {
    showProtocol(e) {
      let num = this.px(56)
      if (num % 2) num--
      if (e) {
        this.height -= num
      } else {
        this.height += num
      }
    }
  },
  onLoad(options) {
    this.type = options.type
    this.orderId = options.orderId
    this.getOrderDetail()
  },
  onShow() {
    this.setVehicle()
    this.setDriver()
  },
  methods: {
    async getOrderDetail() {
      const [err, res] = await getOrderDetail(this.orderId)
      if (!this.$http.errorCheck(err, res)) return false
      const orderInfo = res.data.data
      this.oldPrice = orderInfo.originPrice
      this.ioType = orderInfo.ioType
      this.startDate = orderInfo.startDate.replace(/-/g, '/')
      this.endDate = orderInfo.endDate.replace(/-/g, '/')
      if (orderInfo.ioType && this.type !== 'remark') this.setHeight()
      const obj = {}
      Object.keys(this.form).forEach(key => {
        obj[key] = orderInfo[key]
      })

      if (orderInfo.stopSite) {
        this.stopSite = orderInfo.stopSite
      }
      this.module = orderInfo.itinerary ? 0 : 1
      for (let i = 0; i < products.length; i++) {
        const item = products[i]
        if (item.value === orderInfo.internalProductType) {
          this.productsIndex = i
          break
        }
      }

      // 内部订单
      if (orderInfo.ioType) {
        // 0-自有车辆 1-外调车辆
        obj.vehicleType = orderInfo.vehicleId ? 0 : 1
        // 车辆名称
        if (orderInfo.vehicleId) {
          obj.vehicleName = orderInfo.autoNumber + ' ' + orderInfo.seatAmount + '+1座'
        }
        // 外调车辆
        obj.payWay = orderInfo.outwardVehiclePayWay
        obj.outwardRealPrice = orderInfo.outwardVehicleRealPrice
      } else {
        obj.vehicleName = orderInfo.autoNumber + ' ' + orderInfo.seatAmount + '+1座'
      }

      if (orderInfo.stopSite) {
        obj.stopSite = orderInfo.stopSite.split(',')
      } else {
        obj.stopSite = []
      }
      Object.assign(this.form, obj)
      this.orderInfo = orderInfo
      if (obj.vehicleType) {
        this.setEditOrderSave({
          autoCompanyName: obj.autoCompanyName,
          driverName: obj.driverName,
          driverType: obj.driverType,
          vehicleType: obj.vehicleType
        })
      } else {
        this.setEditOrderSave({
          vehicleId: obj.vehicleId,
          vehicleName: obj.vehicleName,
          vehicleType: obj.vehicleType,
          driverId: obj.driverId,
          driverName: obj.driverName,
          driverType: obj.driverType,
          platformDriverFee: obj.platformDriverFee
        })
      }
    },
    // 设置高度
    setHeight() {
      this.$nextTick(() => {
        const wHeight = this.sysInfo().windowHeight
        this.getElementInfo('#tabBar', res => {
          this.height = wHeight - res.height
          this.getElementInfo('#safe', res => {
            this.height -= res.height
          })
        })
      })
    },
    // 轮播滑动
    onswiperchange(e) {
      this.activeInx = e.target.current || e.detail.current
    },
    // 更新表单信息
    updateFormData(e) {
      Object.assign(this.form, e)
    },
    // 显示修改时间弹窗
    setDate(e) {
      this[e] = true
    },
    // 关闭修改时间弹窗
    close(e) {
      this[e] = false
    },
    // 修改开始时间
    startDateConfirm(e) {
      this.form.startDate = dateFormat(e, 'YYYY-MM-DD hh:mm')
      this.startDate = dateFormat(e, 'YYYY/MM/DD hh:mm',)
      this.endDate = dateFormat(new Date(this.startDate).setHours(new Date(this.startDate).getHours() + 11), 'YYYY/MM/DD hh:mm')
      this.endTimeShow = false
      setTimeout(() => {
        this.endTimeShow = true
      }, 100)
      this.start = false
    },
    // 修改结束时间
    endDateConfirm(e) {
      this.form.endDate = dateFormat(e, 'YYYY-MM-DD hh:mm')
      this.endDate = dateFormat(e, 'YYYY/MM/DD hh:mm')
      this.end = false
    },
    // 选择车辆/司机
    choose(e) {
      const status = this.form.isTaoTuan ? '' : '0'
      const list = JSON.stringify(this[e.type + 'List'])
      const query = '&startDate=' + this.form.startDate +
          '&endDate=' + this.form.endDate +
          '&status=' + status +
          '&chosen=' + list +
          '&excludeTargetIdList=' + this.orderId
      this.jump(e.url + query)
    },
    // 修改车辆信息
    setVehicle() {
      if (this.chooseVehicleInfo) {
        Object.assign(this.form, this.chooseVehicleInfo)
        this.showModal = !!this.chooseVehicleInfo.showModule
        this.setChooseVehicleInfo(null)
      }
    },
    // 修改司机信息
    setDriver() {
      if (this.chooseDriverInfo) {
        Object.assign(this.form, this.chooseDriverInfo)
        this.setChooseDriverInfo(null)
      }
    },
    // 关闭客户名称/手机号/车辆列表
    closeList() {
      if (this.$refs.vehicleModule) this.$refs.vehicleModule.showAutoCompanyName = false
    },
    // 表单验证
    checkForm() {
      for (let i = 0; i < this.mustList.length; i++) {
        const item = this.mustList[i]
        if (!this.form[item.value] && item.condition()) {
          this.toast(item.placeholder)
          return false
        }
      }

      // 自有车辆校验
      if (this.form.vehicleType == 0) {
        if (!this.form.vehicleId) {
          this.toast('请选择车辆')
          return false
        }
        if (this.form.driverType != 2 && !this.form.driverId) {
          this.toast('请选择司机')
          return false
        }
        if (this.form.driverType == 2 && !this.form.driverName) {
          this.toast('请填写司机姓名')
          return false
        }
        if (!this.form.realPrice) {
          this.toast('请输入车费')
          return false
        }
      }

      // 外调车辆校验
      if (this.form.vehicleType == 1) {
        if (!this.form.autoCompanyName) {
          this.toast('请填写车队名称')
          return false
        }
        if (!this.form.realPrice) {
          this.toast('请填写车费')
          return false
        }
        if (this.form.payWay == 3 && !this.form.outwardRealPrice) {
          this.toast('请填写外调车辆费用')
          return false
        }
      }

      if (!checkDate(this.form.startDate, this.form.endDate)) return false

      if (!this.ioType && (parseFloat(this.form.originPrice) > parseFloat(this.oldPrice) || parseFloat(this.form.originPrice) <= 0)) {
        this.toast('租车价格需要大于0元，小于' + this.oldPrice + '元')
        return false
      }

      if (this.showProtocol && !this.isRead) {
        this.toast(`请阅读并勾选《${this.name}司机协议》`)
        return false
      }
      return true
    },
	toast(data,fn = ''){
		uni.showToast({
		     title: data,
		     icon: 'none',
		     duration: 2000//持续的时间
		   })
		 if(fn != ''){
			 setTimeout(()=>{
			 			   fn()
			 },2000)
		 }
	},
    // 下单按钮
    async creatOrder() {
	  const numberRegex = /^\d+(\.\d{1,2})?$/;
	  if(this.form.originPrice > 99999){
	  		  this.toast('车费请输入最大5位数')
	  		  return false
	  }
	  if(this.form.driverSubsidyAmount > 99999){
	  		  this.toast('司机补助请输入最大5位数')
	  		  return false
	  }
	  if(this.form.originPrice && !numberRegex.test(this.form.originPrice)){
		  this.toast('车费请输入最多两位小数的数据类型')
		  return false
	  }
	  if(this.form.driverSubsidyAmount && !numberRegex.test(this.form.driverSubsidyAmount)){
		  this.toast('司机补助请输入最多两位小数的数据类型')
		  return false
	  }
	  if(this.form.remark && this.form.remark.length > 200){
	  		  this.toast('订单备注请输入最多200字')
	  		  return false
	  }
	  if(this.form.driverRemark && this.form.driverRemark.length > 200){
	  		  this.toast('司机备注请输入最多200字')
	  		  return false
	  }
      if (this.type === 'remark') {
        await this.comfirmRemark()
      } else if (this.checkForm()) {
        this.loading = loading('加载中...')
        this.canCreate = false
        if ((this.form.vehicleType == 0 && this.form.driverType == 0) || this.ioType === 0) {
          /* await this.request(bindJudgment, {
            driverId: this.form.driverId,
            vehicleId: this.form.vehicleId,
            type: 1
          })*/
          await this.request(bindJudgmentVehicle, {
            driverId: this.form.driverId,
            vehicleId: this.form.vehicleId,
            startDate: this.form.startDate,
            endDate: this.form.endDate
          })
          // await this.bindLinkDriver(this.form)
        }
        await this.edit()
        this.canCreate = true
      }
    },
    // 关联司机
    async bindLinkDriver(item) {
      const [err, res] = await bindDriver({
        driverId: item.driverId,
        vehicleId: item.vehicleId
      })
      if (!this.$http.errorCheck(err, res)) {
        this.canCreate = true
        return false
      }
    },
    async request(api, data) {
      const [err, res] = await api(data)
      if (!this.$http.errorCheck(err, res)) {
        this.canCreate = true
        return false
      }
      const msg = res.data.data
      if (!msg.status && msg.popupType == 1) {
        this.toast(msg.message)
        this.canCreate = true
      }
    },
    // 确认修改
    async edit() {
      const param = this.copyData(this.form)
      if (param.stopSite && param.stopSite.length > 0) {
        param.stopSite = param.stopSite.join(',')
      } else {
        param.stopSite = ''
      }

      if (!param.fromLat) {
        param.fromLat = '18.252895'
        param.fromLnt = '109.511767'
      }
      if (!param.toLat) {
        param.toLat = '18.252895'
        param.toLnt = '109.511767'
      }
      Object.assign(this.orderInfo, param)
      const [err, res] = await updateOrderAll(this.orderInfo)
      this.loading.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('修改成功', () => {
        this.jump()
      })
    },
    // 修改备注
    async comfirmRemark() {
      const data = {
        orderId: this.orderId,
        remark: this.form.remark
      }
      const [err, res] = await updateOrderRemark(data)
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('修改成功',()=>{
		  this.jump()
	  })
    },
    ...mapMutations({
      setChooseVehicleInfo: 'order/setChooseVehicleInfo',
      setChooseDriverInfo: 'order/setChooseDriverInfo',
      setEditOrderSave: 'order/setEditOrderSave'
    })
  }
}
</script>

<style scoped>
.add-new-container{
  padding:30rpx 30rpx 14rpx;
}
</style>
